interface RequestOptions extends WechatMiniprogram.RequestOption {
  loading?: boolean;
}

const request = <T>(options: RequestOptions): Promise<T> => {
  if (options.loading) {
    wx.showLoading({ title: '加载中...' });
  }

  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      success: (res: any) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          wx.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        reject(err);
      },
      complete: () => {
        if (options.loading) {
          wx.hideLoading();
        }
      }
    });
  });
};

export default request;